<?php

namespace App\Console\Commands\OpenShop;


use App\Enums\OpenShop\InvestmentPromotion\SignOrderEnum;
use App\Enums\OpenShop\MissionTemplateEnum;
use App\Library\Rms\RmsUserApi;
use App\Models\OpenShop\Common\OpenShopOrderManagerModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopMainProcessModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopSignOrderModel;
use App\Service\BaseService;
use App\Service\OpenShop\Feishu\MissionTemplateService;
use App\Service\OpenShop\Import\HistoryOrder\HistoryOrderExecute;
use App\Service\OpenShop\Import\HistoryOrder\HistoryOrderParam;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Log;

class SkipStepMultiple extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'openShop:skip-step-multiple {orderNo?} {stepStatus?}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        $argOrderNo    = (string)$this->argument('orderNo');
        $argStepStatus = (int)$this->argument('stepStatus');

        if (!$argOrderNo || !$argStepStatus) {
            dd('入参不存在');
        }

        $this->info("orderNo:{$argOrderNo} start.........");

        self::doStepSkip($argOrderNo, $argStepStatus, null);

        $this->info("orderNo:{$argOrderNo} end.........");
    }

    /**
     * @param string $argOrderNo
     * @param int $argStepStatus 目标步骤
     * @param object|null $user 强制指定用户
     * @param bool $onlyStep true仅执行一步 false正常执行：逐步执行到指定步骤
     * @return void
     */
    public static function doStepSkip(string $argOrderNo, int $argStepStatus, ?object $forceUser, bool $onlyStep = false): void
    {
        // 关闭所有的event queue
        Config::set('event.connection', 'sync');
        HistoryOrderParam::$importOrderMode = true;
        HistoryOrderParam::$forceCurrentUser = $forceUser;

        $param                    = (new HistoryOrderParam());
        $param->row               = 2;
        $param->signTime          = time();
        $param->contractStartTime = time();
        $param->startBusinessTime = time();

//            $param->stepStatus = MissionTemplateEnum::STEP_STATUS_9; // 最后一步不执行
        $param->stepStatus = $argStepStatus; // 最后一步不执行

        $signOrder = OpenShopSignOrderModel::query()
                                           ->where('orderNo', $argOrderNo)
                                           ->where('status', '!=', SignOrderEnum::ORDER_STATUS_NO)
                                           ->orderByDesc('id')
                                           ->first();

        $nowStepStatus     = $signOrder->mainProcessRel->nowStepStatus;
        $nowStepStatusSort = MissionTemplateService::getSortByStepStatus($nowStepStatus);

        $doStepStatusSort = MissionTemplateService::getSortByStepStatus($param->stepStatus);
        if (!$onlyStep && ($nowStepStatusSort >= $doStepStatusSort)) {
            BaseService::throwErr("当前任务阶段已大于需要执行的阶段");
        }

        if (!$signOrder) {
            BaseService::throwErr("signOrder没有正常记录");
        }

        $baseInfo = $signOrder->baseInfoRel;
        if (!$baseInfo) {
            BaseService::throwErr("baseInfo没有记录");
        }

        $identityInfo = $signOrder->identityCardRel;
        if (!$identityInfo) {
            BaseService::throwErr("identityInfo没有记录");
        }

        $managerUids = $signOrder->orderManagerRel->pluck('managerUid')->toArray();
        $users       = collect((new RmsUserApi)->getUserInfoByIds($managerUids,
                ['id', 'username'])['data'] ?? [])->keyBy('id');

        // 更新order_manager记录
        $managerInfo = $signOrder->orderManagerRel->map(function ($item) use ($users) {

            $username = $users[$item->managerUid]['username'] ?? '';
            if (!$username) {
                return $item;
            }

            $item->managerName = $username;
            $item->save();

            return $item;
        });

        $param->orderNo = $signOrder->orderNo;

        list(
            $param->shopCode,
            $param->name,
            $param->identityNo,
            $param->phone,
            $param->siteMerge,
            $param->siteAddress,
//            $param->isSelfWithAddress,
//            $param->contractTypeText,
//            $param->contractTemplateText,
//            $this->signDate,
//            $this->contractStartDate,
//            $this->startBusinessDate,
            $param->designPrice,
            $param->merchantPrice,
            $param->overDesignPrice,
            $param->equipmentPrice,
            $param->decoratePrice,
            $param->managerSalesName,
            $param->managerDevelopName,
            $param->managerDesignName,
            $param->managerOperateName,
            ) = [
            $signOrder->shopCode,
            $identityInfo->name,
            $identityInfo->identityCardNumber,
            $baseInfo->mobile,
            str_replace('-', '/', $baseInfo->chooseShopAddressPrefix),
            '-',
            0,
            0,
            0,
            0,
            0,
            $managerInfo->where('type', OpenShopOrderManagerModel::MANAGER_TYPE_1)->first()->managerName ?? '石尧（山治）',
            $managerInfo->where('type', OpenShopOrderManagerModel::MANAGER_TYPE_2)->first()->managerName ?? '石尧（山治）',
            $managerInfo->where('type', OpenShopOrderManagerModel::MANAGER_TYPE_3)->first()->managerName ?? '石尧（山治）',
            $managerInfo->where('type', OpenShopOrderManagerModel::MANAGER_TYPE_5)->first()->managerName ?? '石尧（山治）',
        ];
        $param->stepStatusText = MissionTemplateEnum::STEP_STATUS_TEXT[$param->stepStatus];

        $param->prepareParam(1);
        if ($param->getErrMsg()) {
            BaseService::throwErr($param->getErrMsg());
        }

        $main  = OpenShopMainProcessModel::query()->where('orderNo', $param->orderNo)->first();
        $start = $main->nowStepStatus;
        $end   = $param->stepStatus;

        $execute = (new HistoryOrderExecute($param));

        if ($onlyStep) {

            // 仅执行一步
            $execute->doStep($argStepStatus);

        } else {

            // 跳转到指定步骤
            $go        = false;
            $stepLists = json_decode(OpenShopMainProcessModel::query()->where('orderNo', $param->orderNo)
                                                             ->value('stepStatusLists'), true);

            foreach ($stepLists as $stepStatus) {
                if ($stepStatus == $start) {
                    $go = true;
                }

                if ($stepStatus == $end) {
                    $go = false;
                }

                if ($go) {
                    Log::info("do orderNo: {$argOrderNo}" . $stepStatus);
                    $execute->doStep($stepStatus);
                }
            }
        }
    }
}
